/**
 * 设置预加载
 */
function load() {
    setTimeout(function () {
        // 关闭加载类
        $('.placeholder').removeClass('placeholder')
    }, DELAY_LOAD_INDEX)
    setTimeout(function () {
        // 关闭加载类
        $('.placeholder-wave').removeClass('placeholder-wave')
    }, DELAY_LOAD_INDEX_WAVE)
}
load()
///// 当前页面的分页信息

let page_current = 0
let page_size = 0

///// 渲染商品
function renderIndexProduct(arrayData){
    $entry = $('#index-product-render-entry')
    // 清空
    $entry.html('')
    $.each(arrayData, (index, product) => {
            $entry.append(`
             <li class="px-3 mt-3">
                <div class="card" style="height: 350px;">
                    <a href="/product.html?productId=${product['id']}">
                        <img src="${product.img}" class="card-img-top placeholder-wave" width="250px" height="220px">
                    </a>
                    <div class="card-body">
                        <h5 class="card-title placeholder" style="font-size: 0.9rem;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;">
                            ${product.name}
                          </h5>
                        <p class="card-text placeholder" style="font-size: 0.8rem">商品分类:${product.category.name}</p>
                        <p class="card-text placeholder" style="font-size: 0.8rem">商品价格:<span class="fw-bolder text-danger">￥${product.price}</span></p>
                    </div>
                </div>
            </li>
        `)
    })
    load()
}

///// 跳转到指定页
function toPage(inputId){
    $input = $('#' + inputId)
    let page = $input.val()
    // 限制页面的范围
    page = Math.min(page, page_size)
    page = Math.max(page, 1)
    location.href = paramUpdateCurrentParam('pageNum', page)
}
///// 渲染分页
function renderIndexPage(pageData){
    $entry = $('#index-page-render-entry')
    $entry.html('')
    $perPage = $(`<li></li>`)
    // 渲染尾部
    $tail = `<li class="align-self-center r">
                &nbsp;&nbsp;到第&nbsp;&nbsp;
            </li>
            <li class="align-self-center">
                <input id="index-input-to-page" class="input-group" name="pageNum" size="5">
            </li>
            <li class="align-self-center">
                &nbsp;页&nbsp;
            </li>
            <li class="align-self-center">
                <button class="btn btn-outline-dark" onclick="toPage('index-input-to-page')">确定</button>
            </li>`
    // 渲染每一页
    let current = pageData['current']
    let pages = pageData['pages']
    page_current = current
    page_size = pages
    let page_pre = Math.max(current - 1, 1)
    let page_next = Math.min(current + 1, pages)
    for (let index = -2; index <= 2; index++) {
        let pageNum = current + index
        if(pageNum <= 0 || pageNum > pages) continue

        if(current === pageNum){ // 渲染当前页，设置一个高亮的效果
            $perPage.append(`
            <li class="page-item mx-2 active" aria-current="page">
             <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', pageNum)}">${pageNum}</a>
         </li>`)
        } else {
            $perPage.append(`
             <li class="page-item mx-2" aria-current="page">
                 <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', pageNum)}">${pageNum}</a>
             </li>`
            )
        }
    }
    $entry.html('')
    $entry.html(`
            <ul class="pagination mx-auto justify-content-center">
            <li class="align-self-center me-3 rounded-3">
                    第 ${page_current} 页 &nbsp;&nbsp; 共 ${page_size} 页
            </li>
            <li class="page-item ms-page">
                 <a class="page-link" href="${paramUpdateCurrentParam('pageNum', 1)}">
                    首页
                 </a>
            </li>
            <!--上一页-->
           <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page_pre)}">上一页</a>
            </li>`
             + $perPage.html() + `
            <!--下一页-->
             <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page_next)}">下一页</a>
            </li>
            <!--最后一页-->
             <li class="page-item ms-page" href="/index.html?pageNum=${pages}">
                  <a class="page-link" href="${paramUpdateCurrentParam('pageNum', pages)}">末页</a>
             </li>` + $tail +
        `</ul>`)
}
// 渲染分类
function renderCategory(jsonData) {
    $entry = $('#index-category-render-entry')
    $entry.html(`<ul class="list-unstyled list-group list-group-horizontal"></ul>`)
    $entry = $entry.children('ul')
    let sum = 0
    $.each(jsonData, (index, category)=>{
        sum += eval(category['sum'])
        $entry.append(`
            <li class="mx-2">
                <a type="button" class="btn btn-light position-relative" href="${paramUpdateCurrentParam('category', category['id'])}">
                  ${category['name']}
                  <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-dark">
                    ${category['sum']}
                    <span class="visually-hidden"></span>
                  </span>
                </a>
            </li>
        `)
    })
    $entry.prepend(`
                <li class="mx-2">
                    <a type="button" class="btn btn-light position-relative" href="${paramDeleteCurrentURLNot('category')}">
                      全部商品
                      <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-dark">
                        ${sum}
                        <span class="visually-hidden"></span>
                      </span>
                    </a>
                </li>
    `)
}
///// 获取商品数据
function ajaxGetAllProduct(){
    $.ajax({
        url: '/product/query',
        type: 'POST',
        data:  paramGetURLtoJSON(),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        error: (err) =>{
            ms_show_toast(false, 'AJAX请求失败:' + err.responseText)
            console.error(err.responseText)
        },
        success: (result) =>{
            if(result.code === CODE_SUCCESS){
                console.log(result['data'])
                setTimeout(function (){
                    renderIndexProduct(result['data']['records'])
                }, DELAY_INDEX_PRODUCT_APPEARED)
                renderIndexPage(result['data'])
                $('#index-span-product-sum').text(result['data']['total'])
            }
        }
    })
}


//// 获取分类数据
function ajaxGetAllCategory(){
    $.ajax({
        url: '/category/query',
        type: 'POST',
        dataType: 'JSON',
        error: (err) =>{
            ms_show_toast(false, 'AJAX请求失败:' + err.responseText)
            console.error(err.responseText)
        },
        success: (result) => {
            if(result.code === CODE_SUCCESS){
                renderCategory(result['data'])
            }
        }
    })
}


function renderSearch() {
    let ignore = ['pageNum']
    $entry = $('#index-ul-search-render-entry')
    $entry.html('')
    map = paramGetURLtoMap()
    if(map.size > 0) {
        map.forEach(function (value, flag) {
            if (ignore.includes(flag)) return true
            $entry.append(`
                <div class="alert alert-warning alert-dismissible fade show pt-2 pb-2 mx-2" role="alert">
                  <strong>${flag} = ${decodeURI(value)}</strong> 
                  <button type="button" class="btn-close ms-btn-small pt-2" data-bs-dismiss="alert" aria-label="Close" onclick="paramDeleteCurrentURL('${flag}')"></button>
                </div>`)
        })
    }
}

/// 搜索范围
$('#index-btn-search-price').click(function (){
    let minPrice = $('#index-search-price-mini').val()
    let maxPrice = $('#index-search-price-maxi').val()
    // 限制搜索的范围
    minPrice = Math.max(minPrice, 1)
    maxPrice = Math.min(maxPrice, 999999)
    maxPrice = Math.max(maxPrice, minPrice)
    let url = paramUpdateURL(location.href, 'miniPrice', minPrice)
    url = paramUpdateURL(url, 'maxPrice', maxPrice)
    location.href = url
})
// 搜索
function toSearch(){
    text = $('#index-input-search').val()
    location.href = paramUpdateCurrentParam('name', text)
}
// 试试自动登录
$(document).ready(function (){
    $.ajax({
        url: '/user/autoLogin',
        type: 'POST',
        success: function (result){
            if(result['code'] === CODE_SUCCESS)
                ms_show_toast(true, result['msg'], function (){
                    location.reload()
                })
        }
    })
    ajaxGetAllProduct()
    ajaxGetAllCategory()
    renderSearch()
})